package com.shloma.bbts.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.shloma.bbts.entity.SysConfig;
import com.shloma.bbts.service.SysConfigService;
import com.shloma.bbts.tcp.client.RequestBankClient;
import com.shloma.bbts.tcp.client.RequestCorpClient;
import com.shloma.bbts.tcp.server.ReceiveBankRequestServer;
import com.shloma.bbts.tcp.server.ReceiveCorpRequestServer;
import com.shloma.bbts.utils.BeanFactoryUtils;

@Service
public class TcpUtils {

	private static Logger logger = LoggerFactory.getLogger(TcpUtils.class);

	public void startServer() {
		SysConfigService configService = BeanFactoryUtils.getBean(SysConfigService.class);
		ReceiveCorpRequestServer receiveCorpRequestServer = BeanFactoryUtils.getBean(ReceiveCorpRequestServer.class);
		ReceiveBankRequestServer receiveBankRequestServer = BeanFactoryUtils.getBean(ReceiveBankRequestServer.class);
		RequestBankClient requestBankClient = BeanFactoryUtils.getBean(RequestBankClient.class);
		RequestCorpClient requestCorpClient = BeanFactoryUtils.getBean(RequestCorpClient.class);

		SysConfig querySysConfig = configService.querySysConfig();
		receiveCorpRequestServer.startServer(querySysConfig.getCorpServerPort(), querySysConfig.getCorpPkgEncode());
		receiveBankRequestServer.startServer(querySysConfig.getBankServerPort(), querySysConfig.getCorpPkgEncode());

		requestBankClient.initClient(querySysConfig.getBankIp(), querySysConfig.getBankPort());
		requestCorpClient.initClient(querySysConfig.getCorpIp(), querySysConfig.getCorpPort());
	}

	public void stopServer() {
		ReceiveCorpRequestServer receiveCorpRequestServer = BeanFactoryUtils.getBean(ReceiveCorpRequestServer.class);
		ReceiveBankRequestServer receiveBankRequestServer = BeanFactoryUtils.getBean(ReceiveBankRequestServer.class);

		receiveCorpRequestServer.stopServer();
		receiveBankRequestServer.stopServer();
	}

	public static byte[] readDataFromChannel(SocketChannel socketChannel) {
		ByteBuffer receiveByteBuffer = ByteBuffer.allocate(1024);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
		try {
			int readSize = 0;
			while ((readSize = socketChannel.read(receiveByteBuffer)) > 0) {
				// 读写转换
				receiveByteBuffer.flip();
				byteArrayOutputStream.write(receiveByteBuffer.array(), 0, readSize);
			}
			byteArrayOutputStream.flush();

			byte[] byteArray = byteArrayOutputStream.toByteArray();
			return byteArray;
		} catch (IOException e) {
			logger.error("###### read data from socketChannel error!!!", e);
			throw new RuntimeException("从通道中读取数据异常");
		}
	}
}
